<template>
  <div>
    <el-dialog
      :title="title"
      v-model="state.isShow"
      lock-scroll
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      draggable
      align-center
      width="400px"
      @closed="closed"
    >
      <div v-loading="state.updating">
        <el-input v-model="state.name" :placeholder="placeholder"></el-input>
      </div>
      <template #footer>
        <el-button @click="closed">取 消</el-button>
        <el-button
          :disabled="state.updating"
          :loading="state.updating"
          type="primary"
          @click="confirm"
          >确 定</el-button
        >
      </template>
    </el-dialog>
  </div>
</template>
<script setup lang="ts">
import { message } from "@/utils/message";
import { debounce } from "lodash-es";
import { reqUserBecomeAgent } from "@/api/user";

const props = withDefaults(
  defineProps<{
    level: string;
    pid: number | null;
  }>(),
  {
    level: "二",
    pid: null
  }
);
const emit = defineEmits(["update"]);
const state = reactive({
  updating: false,
  isShow: false,
  name: ""
});
const placeholder = computed(() => {
  return `请输入${props.level}级代理用户名`;
});
const title = computed(() => {
  return `添加${props.level}级代理`;
});
const closed = () => {
  state.isShow = false;
};
const open = () => {
  state.isShow = true;
};
const confirm = debounce(
  async () => {
    if (!state.name) {
      message.error(placeholder.value);
      return;
    }
    try {
      state.updating = true;
      const params = {
        Name: state.name,
        ParentId: props.pid
      };
      await reqUserBecomeAgent(params);
      state.name = "";
      emit("update");
      message.success(`添加${props.level}级代理成功`);
      setTimeout(() => {
        closed();
      }, 200);
    } catch (error) {
      console.log(error);
    }
    state.updating = false;
  },
  500,
  { leading: true, trailing: false }
);

defineExpose({
  open
});
</script>
<style scoped lang="scss">
:deep(.el-dialog__body) {
  padding: 10px 20px 10px 20px;
}
</style>
